<template>
	<div class="system-dic-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div v-if="loading" class="loading-container">
				<el-skeleton avatar paragraph="8" />
			</div>
			<div v-else>
				<!-- 遍历分组数据，渲染每个分组 -->
				<div v-for="(group, groupIndex) in groupList" :key="group.id" class="group-box">
					<h3 class="group-title">{{ group.title }}</h3>
					<!-- 动态添加输入 + 按钮 -->
					<div class="add-row">
						<el-input v-model="group.newOptionLabel" size="default" placeholder="输入新选项名称(label)" class="add-input" />
						<el-input v-model="group.newOptionValue" size="default" placeholder="输入新选项值(value)" class="add-input" />
						<el-button type="primary" @click="addOption(groupIndex)" size="default">
							添加选项
						</el-button>
					</div>
					<!-- 复选框组 -->
					<el-checkbox-group v-model="group.checked_values" >
						<div class="flex flex-wrap gap-2">
							<el-checkbox v-for="(option, optIndex) in group.options" :key="option.value"
								:value="option.value" :title="option.label" class="flex items-center">
								{{ option.label }}
								<el-button link style="padding: 0;color:red;font-size:12px;margin-bottom:2px" @click.stop="removeOption(groupIndex, optIndex)">
									删除
								</el-button>
							</el-checkbox>
						</div>
					</el-checkbox-group>
					<!-- 每组单独保存按钮 -->
					<div style="margin-top:12px;" v-auth="'/comm/plugins/edit'">
						<el-button type="primary" size="default" @click="saveGroup(groupIndex)" :loading="group.loading">保存</el-button>
					</div>
				</div>
			</div>
		</el-card>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { commApi } from '/@/api/comm/index';
import { ElMessageBox, ElMessage } from 'element-plus';
// 状态管理
const loading = ref(true);
const groupList = ref([]);

// 获取接口数据
const fetchData = async () => {
    try {
        loading.value = true;
        let res = await commApi().plugins();
        // 适配接口数据，补充前端需要的字段
        groupList.value = (res.data.list || []).map(group => ({
            ...group,
            newOptionLabel: '',
            newOptionValue: '',
            loading:false,
            checked_values: Array.isArray(group.checked_values) ? group.checked_values : [],
            options: Array.isArray(group.options) ? group.options : []
        }));
    } catch (error) {
        ElMessage.error('获取数据失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};
// 添加选项
const addOption = async (groupIndex) => {
    const group = groupList.value[groupIndex];
    const label = group.newOptionLabel.trim();
    const value = group.newOptionValue.trim();

    if (!label || !value) {
        ElMessage.warning('名称和值都不能为空');
        return;
    }

    // 检查 value 是否唯一
    const exists = group.options.some(option => option.value === value);
    if (exists) {
        ElMessage.warning(`值 "${value}" 已存在`);
        return;
    }
    group.options.push({
        label, value
    });
    group.newOptionLabel = '';
    group.newOptionValue = '';
};

// 删除选项
const removeOption = async (groupIndex, optIndex) => {
    const group = groupList.value[groupIndex];
    const optionToRemove = group.options[optIndex];
    // 从已选值中移除
    group.checked_values = group.checked_values.filter(
        val => val !== optionToRemove.value
    );
    // 从选项列表中删除（保险起见）
    group.options = group.options.filter(opt => opt.value !== optionToRemove.value);
};

// 保存本组
const saveGroup = async(groupIndex) => {
    const group = groupList.value[groupIndex];
    const result = {
        id: group.id,
        title: group.title,
        status:group.status,
        checked_values: group.checked_values,
        options: group.options
    };
    try {
        groupList.value[groupIndex].loading = true
        let res = await commApi().pluginsEdit(result);
        ElMessage.success(`【${group.title}】已保存`);
    } catch (error) {
        ElMessage.error(error);
    } finally {
        groupList.value[groupIndex].loading = false
    }
};

// 页面加载时获取数据
onMounted(() => {
    fetchData();
});
</script>

<style scoped>
.dynamic-checkbox-group {
	padding: 20px;
	border: 1px solid #e4e7ed;
	border-radius: 4px;
	background-color: #fff;
}

.group-box {
	margin-bottom: 20px;
	padding-bottom: 20px;
	border-bottom: 1px solid #eee;
}

.group-box:last-child {
	border-bottom: none;
	margin-bottom: 0;
	padding-bottom: 0;
}

.group-title {
	font-size: 16px;
	font-weight: bold;
	margin-bottom: 10px;
}

.add-row {
	display: flex;
	align-items: center;
	gap: 10px;
	margin-bottom: 10px;
}

.add-input {
	width: 180px;
}

.checkbox-item {
	display: flex;
	align-items: center;
	margin-right: 20px;
	margin-bottom: 10px;
}

.delete-btn {
	color: #f44336;
	margin-left: 4px;
	/* 调整间距，确保文字按钮与选项之间有足够空间 */
}

.loading-container {
	padding: 20px;
}
</style>
